package com.lemon.es;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IndexManager {


    private TransportClient transportClient;

//     单节点配置和初始化
    @Before
    public void before() throws  Exception{
        //1、创建一个Settings对象，相当于一个配置信息。主要配置集群的名称。
        Settings settings = Settings.builder()
                .put("cluster.name", "docker-cluster")//设置集群名称
                .put("client.transport.ping_timeout", "30s")
                .put("client.transport.nodes_sampler_interval", "15s")
                .put("client.transport.sniff", false).build();//自动嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中
        transportClient = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.75.128"), 9300));

/*        Settings settings = Settings.EMPTY;// 告诉你采用的是默认配置
        transportClient  = new PreBuiltTransportClient(settings);
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.50.37"),9300));
//        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.15.23"),9300));*/
    }


    // 集群配置和初始化
//    @Before
//    public void before() throws  Exception{
//        //1、创建一个Settings对象，相当于一个配置信息。主要配置集群的名称。
//        Settings settings = Settings.builder().put("cluster.name","cluster-es").build();// 告诉你采用的是默认配置
//        transportClient  = new PreBuiltTransportClient(settings);
//        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
//        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9301));
//        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9302));
//    }


    // 1： 创建索引库
    @Test
    public void crateIndexResp(){
        System.out.println(transportClient);
        //底层原理，javaapi会自动组装：http://localhost:9200/blog2 ---put
        CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
        System.out.println(response.index());
    }





    // 2：创建mapping规则
    @Test
    public void createMapping() throws  Exception{
        CreateIndexResponse response = transportClient.admin().indices().prepareCreate("blog2").get();
        if(response.isAcknowledged()) {
            // 1: 建立json规则
//            XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject()
//                    .startObject("content")
//                       .startObject("properties")
//
//                            .startObject("id").field("type", "long").field("store", true).endObject()
//                            .startObject("operator").field("type","text").field("store",true).endObject()
//                            .startObject("time").field("type","date").field("format","yyyy-MM-dd HH:mm:ss").endObject()
//                            .startObject("method").field("type","text").field("store",true).endObject()
//                            .startObject("param").field("type","text").field("store",true).endObject()
//                    // 细粒度切分使用 ik_max_word  最小切分 ik_smart
////                    .startObject("title").field("type", "text").field("store", true).field("analyzer", "ik_smart").endObject()
////                    .startObject("content").field("type", "text").field("store", true).field("analyzer", "ik_smart").endObject()
//                       .endObject()
//                    .endObject();

            //创建mapping约束字段
            XContentBuilder mapping = XContentFactory.jsonBuilder()
                    .startObject()
                       .startObject("properties")
                           .startObject("operator")
                                .field("type","keyword")
                           .endObject()
                           .startObject("time")
                                .field("type", "date").field("format","yyyy-MM-dd HH:mm:ss")
                           .endObject()
                           .startObject("method")
                                .field("type","text")
                           .endObject()
                           .startObject("param")
                               .field("type", "text")
                           .endObject()
                       .endObject()
                    .endObject();

//            Map<String,Object> map = new HashMap<String, Object>();
//            Map<String,Object> propertiesMap = new HashMap<String, Object>();
//            Map<String,Object> properties = new HashMap<String, Object>();
//
//
//            Map<String,Object> idMap = new HashMap<String, Object>();
//            idMap.put("type","long");
//            idMap.put("store",true);
//            properties.put("id",idMap);
//
//            Map<String,Object> titleMap = new HashMap<String, Object>();
//            titleMap.put("type","text");
//            titleMap.put("analyzer","ik_smart");
//            titleMap.put("store",true);
//            properties.put("title",titleMap);
//
//            Map<String,Object> contentMap = new HashMap<String, Object>();
//            contentMap.put("type","text");
//            contentMap.put("analyzer","ik_smart");
//            contentMap.put("store",true);
//            properties.put("content",contentMap);
//
//
//            propertiesMap.put("properties",properties);
//
//            map.put("content",propertiesMap);
//
//            // 2: 把pojo转换成json格式
//            ObjectMapper objectMapper = new ObjectMapper();
//            String jsonString =  objectMapper.writeValueAsString(map);
//            System.out.println(jsonString);

            // 执行规则 报错，创建规则不会创建索引库和类型，就报错。
            PutMappingResponse putMappingResponse = transportClient.admin().indices().preparePutMapping("blog2").setType("content").setSource(mapping).get();
            System.out.println(putMappingResponse.isAcknowledged());

            // 关闭
            transportClient.close();
        }

    }


    // 3:添加/修改文档--方式一XContentBuilder
    @Test
    public void createIndex() throws  Exception{
        // 转变json数据

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        String time = simpleDateFormat.format(date);
        Content content = new Content(25,"害虫","昆虫学研究所");

        XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject()
                .field("operator","lemon") //
                .field("time",time) //
                .field("method","批量增加学生")
                .field("content",content)
                .endObject();


        // 创建索引
//        IndexResponse indexResponse = transportClient.prepareIndex("blog2","content","1")
//                .setSource(contentBuilder).get();
        // 如果在创建索引的时候，你没有指定文档id,es服务会自动分配一个主键ID，作为文档唯一标识符。
        // 如果文档主键ID,如果相同就是修改。
        IndexResponse indexResponse = transportClient.prepareIndex("blog2","error")
                .setSource(contentBuilder).get();
        System.out.println(indexResponse.status());

        // 关闭
        transportClient.close();
    }


    // 添加/修改文档--pojo
    @Test
    public void createIndexForPojo() throws  Exception{

        // 1:  准备数据
        Content content = new Content();
        content.setId(3);
        content.setTitle("solr是一个基于lucene的搜索服务");
        content.setContent("solr是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎，基于RESTful web接口。Elasticsearch是用Java开发的，并作为Apache许可条款下的开放源码发布，是当前流行的企业级搜索引擎。设计用于云计算中，能够达到实时搜索，稳定，可靠，快速，安装使用方便");

        // 2: 把pojo转换成json格式
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString =  objectMapper.writeValueAsString(content);


        // 3 :如果文档主键ID,如果相同就是修改。
        IndexResponse indexResponse = transportClient.prepareIndex("blog2","content",content.getId()+"")
                .setSource(jsonString).get();
        System.out.println(indexResponse.status());
        // 4 :关闭
        transportClient.close();
    }



    // 删除文档
    @Test
    public void deleteIndex(){
       DeleteResponse deleteResponse = transportClient.prepareDelete(".kibana","doc","space:default").get();
       //DeleteResponse deleteResponse = transportClient.delete(new DeleteRequest("blog2", "article", "1")).get();
       System.out.println(deleteResponse.status());
        // 关闭 transportClient
        transportClient.close();

    }



    @Test
    public void lemon(){
    int in = 781;
    int total = 805;

    if(in == (float)in /(float)total *100){
        System.out.println("");
    }
    }

    public static void main(String[] args) {
        /**
         * 判断是否含有特殊字符
         *
         * @param str
         * @return true为包含，false为不包含
         */

           String  str=  "$中山市第一{小学$";
            // String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
            String regEx = "[ _.`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(str);

            if (m.find() && str.trim().length() >=4 && str.trim().length()<=32 ){
                System.out.println("1");
            }

            if( str.trim().length() >=4){
                System.out.println("2");
            }

            if( str.trim().length() <=32){
                System.out.println("3");
            }





    }














}
